package com.xmtlxx.sacw.service.base;

import com.xmtlxx.common.core.domain.dto.RoleDTO;
import com.xmtlxx.common.core.domain.model.LoginUser;
import com.xmtlxx.common.helper.LoginHelper;
import com.xmtlxx.system.service.ISysDataScopeService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * sacw基本实现服务
 *
 * @author hergreen
 * @date 2024/07/19 14:02
 **/
public class SacwBaseService {

    @Autowired
    private ISysDataScopeService iSysDataScopeService;

    public List<String> getUserDataScopes() {

        List<String> officeList = new ArrayList<>();
        if (LoginHelper.isAdmin()) {
            return iSysDataScopeService.selectDeptCodesByRoleIds(null, null, null, null);
        }
        if (LoginHelper.isTenantAdmin()) {
            return iSysDataScopeService.selectDeptCodesByRoleIds(null, null, null, LoginHelper.getTenantId());
        }

        LoginUser user = LoginHelper.getLoginUser();
        if (user != null && user.getRoles() != null && user.getRoles().size() > 0) {
            List<String> scopes = user.getRoles().stream().map(RoleDTO::getDataScope).collect(Collectors.toList());
            List<Long> roleIds = user.getRoles().stream().map(RoleDTO::getRoleId).collect(Collectors.toList());

            scopes.forEach(scope -> {
                if ("1".equals(scope)) {//全部
                    officeList.addAll(iSysDataScopeService.selectDeptCodesByRoleIds(null, null, null, null));
                } else if ("2".equals(scope)) {//自定数据权限
                    officeList.addAll(iSysDataScopeService.selectDeptCodesByRoleIds(null, null, roleIds, null));
                } else if ("3".equals(scope)) {//部门数据权限
                    officeList.addAll(iSysDataScopeService.selectDeptCodesByRoleIds(user.getDeptId(), null, null, null));
                } else if ("4".equals(scope)) {//部门及以下数据权限
                    officeList.addAll(iSysDataScopeService.selectDeptCodesByRoleIds( null, user.getDeptId(), null, null));
                } else if ("5".equals(scope)) {//仅本人数据权限
                    officeList.addAll(iSysDataScopeService.selectDeptCodesByRoleIds(user.getDeptId(), null, null, null));
                }
            });
        }
        return officeList;
    }
}
